///////////////////////////////////////////////////////////////////////////////
//
//  This source is part of the  "Managed Task Framework.NET Runtime"  (MTF.NET Runtime).
//
//
//  Copyright (c) 2011, Multicore Consulting Limited (UK)
//  All rights reserved.
//  http://www.multicoreconsulting.co.uk
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions
//  are met:
//
//  -  Redistributions of source code must retain the above copyright
//     notice, this list of conditions and the following disclaimer.
//  -  Redistributions in binary form must reproduce the above copyright
//     notice, this list of conditions and the following disclaimer in
//     the documentation and/or other materials provided with the
//     distribution.
//  -  Neither the name of Multicore Consulting Limited nor the names of
//     its contributors may be used to endorse or promote products
//     derived from this software without specific prior written
//     permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//  COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//  POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////

using global::MTFOrg.MTF.MTFRuntime;
using global::MTFOrg.MTF.MTFCore;
using System.Collections.Generic;
using System.Windows.Threading;
using System;

namespace MTFOrg.MTF.MTFBlocks
{
    public class UiConnector
    {
        /// <summary>
        /// Defines the subscriber delegate.
        /// </summary>
        /// <param name="data">Data object sent to subscriber</param>
        public delegate void SubscriberCallback(EventDictionary actionEvent, int elementNumber);

        /// <summary>
        /// Subscriber description.
        /// </summary>
        protected class Subscriber
        {
            public SubscriberCallback SendData;
        }

        /// <summary>
        /// Singleton instance.
        /// </summary>
        public static UiConnector m_Instance;

        /// <summary>
        /// Dictionary of subscribers to named channels.
        /// </summary>
        protected Dictionary<string, Subscriber> m_Subscribers;

        /// <summary>
        /// Dispatcher for the main window.
        /// </summary>
        protected Dispatcher m_WindowDispatcher;

        /// <summary>
        /// Constructor.
        /// </summary>
        protected UiConnector()
        {
            m_Subscribers = new Dictionary<string, Subscriber>();
        }

        /// <summary>
        /// Gets the singleton instance.
        /// </summary>
        protected static UiConnector Instance
        {
            get
            {
                if (m_Instance == null) m_Instance = new UiConnector();
                return m_Instance;
            }
        }

        /// <summary>
        /// Initializes the publisher. MUST BE CALLED FROM GUI THREAD.
        /// </summary>
        public static void Initialize()
        {
            Instance.m_WindowDispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher;
        }

        /// <summary>
        /// Registers a subscriber with a publisher.
        /// </summary>
        /// <param name="channelName">Channel name to subscribe to</param>
        /// <param name="subscriber">Delegate to subscribe</param>
        public static void Register(string channelName, SubscriberCallback subscriber)
        {
            CreateChannel(channelName);
            Instance.m_Subscribers[channelName].SendData += subscriber;
        }

        /// <summary>
        /// Unregisters a subscriber from a publisher.
        /// </summary>
        /// <param name="channelName">Channel name to unsubscribe from</param>
        /// <param name="subscriber">Delegate to unsubscribe</param>
        public static void Unregister(string channelName, SubscriberCallback subscriber)
        {
            if (Instance.m_Subscribers.ContainsKey(channelName))            
                Instance.m_Subscribers[channelName].SendData -= subscriber;
        }

        /// <summary>
        /// Sends the specified data object on the specified channel.
        /// </summary>
        /// <param name="channelName">Channel name</param>
        /// <param name="data">Data object to send</param>
        public static void Send(string channelName, EventDictionary actionEvent, int elementNumber)
        {
            if (Instance.m_Subscribers.ContainsKey(channelName))
            {
                Dispatcher dispatcher = Instance.m_WindowDispatcher;

                if (dispatcher != null)
                {
                    dispatcher.Invoke((Action)delegate()
                    {
                        SubscriberCallback subscriberCallback = Instance.m_Subscribers[channelName].SendData;

                        if (subscriberCallback != null)
                            subscriberCallback(actionEvent, elementNumber);
                    });
                }
            }
        }

        public static ICollection<string> GetAllChannelNames()
        {
            return Instance.m_Subscribers.Keys;
        }

        public static void CreateChannel(string channelName)
        {
            if (!Instance.m_Subscribers.ContainsKey(channelName))
                Instance.m_Subscribers.Add(channelName, new Subscriber());
        }
    }

    public class Processing : Actioner.Handler
    {
        public override void OnInitialize()
        {
            base.OnInitialize();

            string channelName = OwningActioner.ParentTask.GetProperty("ChannelName") as string;
            UiConnector.CreateChannel(channelName);
        }

        public override void OnAction(Actioner actioner, EventDictionary actionEvent, int elementNumber)
        {
            string channelName = actioner.ParentTask.GetProperty("ChannelName") as string;
            UiConnector.Send(channelName, actionEvent, elementNumber);
        }
    }
}
